package com.nutrition.health.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * Spring Security配置类
 * 配置安全相关的设置，包括密码加密、CORS、CSRF等
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置HTTP安全策略
     * @param http HttpSecurity对象
     * @throws Exception 配置异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors().and()
            .csrf().disable()  // 禁用CSRF，因为我们使用的是无状态的REST API
            .authorizeRequests()
                .antMatchers("/users/register", "/users/login").permitAll()  // 允许注册和登录接口的匿名访问
                .antMatchers("/v2/api-docs", "/swagger-ui/**", "/swagger-resources/**").permitAll()  // 允许Swagger文档的匿名访问
                .antMatchers("/**").permitAll()  // 暂时允许所有接口的访问，后续可以根据需要调整
            .and()
            .httpBasic().disable()  // 禁用HTTP Basic认证
            .formLogin().disable();  // 禁用表单登录
    }

    /**
     * 密码编码器Bean
     * 用于对密码进行加密和验证
     * @return BCryptPasswordEncoder实例
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * CORS配置源Bean
     * 配置跨域资源共享策略
     * @return CorsConfigurationSource实例
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));  // 允许所有来源
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));  // 允许的HTTP方法
        configuration.setAllowedHeaders(Arrays.asList("*"));  // 允许所有头部
        configuration.setAllowCredentials(true);  // 允许发送凭证
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);  // 对所有路径应用这个配置
        return source;
    }
}